using System;
using System.Collections.Generic;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using Navigant.Infrastructure.Cases;
using Navigant.Infrastructure.Helpers;
using Navigant.Model.Custodians;

namespace Navigant.Web.UI
{
	public class CustodianSendList : ListControl
    {
        #region Fields

        private List<Custodian> checkedCustodians;
        private List<Custodian> custodians;
		private Dictionary<string, string> custodianLetters;
		private HtmlInputHidden historyHidden;
        private ICase currentCase;
        private bool paging;

        #endregion

        #region Constructors

        public CustodianSendList(ICase currentCase, int scrollHeight, 
            bool paging)
		{
            this.currentCase = currentCase;
            this.custodians = new List<Custodian>();
			this.ContentHeight = scrollHeight;
            this.paging = paging;
            this.custodianLetters = new Dictionary<string, string>();
            this.EnableViewState = false;
		}

        #endregion

        #region SetCustodians

        public void SetCustodians(IList<Custodian> custodians)
        {
            this.custodians = new List<Custodian>(custodians);
            this.BindCustodians();
        }

        #endregion

        #region BindCustodians

        private void BindCustodians()
        {
            if (this.custodians == null)
            {
                return;
            }
            string uniqueId = string.Empty;
            foreach (Custodian custodian in this.custodians)
            {
                uniqueId = this.GetCustodianUniqueId(custodian);
                foreach (string key in this.Page.Request.Params.Keys)
                {
                    if (key.IndexOf(uniqueId) > -1 && this.Page.Request[key] == "on")
                    {
                        this.checkedCustodians.Add(custodian);
                    }
                }
                if (!this.currentCase.ClientPortal.ShowNonPersonCustodiansInNoticeSending)
                {
                    if (custodian.IsPerson)
                    {
                        this.AddGridCustodianRow(custodian);
                    }
                }
                else
                {
                    this.AddGridCustodianRow(custodian);
                }
            }
        }

        #endregion

        #region Properties

        public IList<Custodian> SelectedCustodians
        {
            get { return this.checkedCustodians; }
        }

		public Custodian HistoryCustodian
		{
			get
			{
				string historyUniqueId = this.Page.Request[this.historyHidden.UniqueID];
				
				if (!string.IsNullOrEmpty(historyUniqueId))
				{
                    string uniqueId = string.Empty;
					foreach (Custodian custodian in this.custodians)
					{
						uniqueId = this.GetCustodianUniqueId(custodian);
                        if (uniqueId == historyUniqueId)
                        {
                            return custodian;
                        }
					}
				}

				return null;
			}
		}

        #endregion

        #region ClearCustodianSelection

        public void ClearCustodianSelection(Custodian custodian)
		{
			this.checkedCustodians.Remove(custodian);
		}

        #endregion

        #region OnInit

        protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);

			try
			{
                this.checkedCustodians = new List<Custodian>();
			    this.Title = "Case Custodians";
                this.historyHidden = new HtmlInputHidden();
				this.Controls.Add(this.historyHidden);

				HtmlTableCell cell = this.CreateHeaderCell(1);
				cell.InnerHtml = "&nbsp;";
				cell.Width = "15";

				cell = this.CreateHeaderCell(10);

				LinkButton sortButton = new LinkButton();
				sortButton.Text = "Name";
				sortButton.Click += new EventHandler(this.SortButtonClick);
				cell.Controls.Add(sortButton);

				cell = this.CreateHeaderCell(10);

				sortButton = new LinkButton();
				sortButton.Text = "Status";
				sortButton.Click += new EventHandler(this.SortButtonClick);
				cell.Controls.Add(sortButton);
			}
			catch (Exception ex)
			{
                Logger.LogError(ex, this.currentCase);
			}
		}

        #endregion

        #region OnPreRender

        protected override void OnPreRender(EventArgs e)
		{
            base.OnPreRender(e);
            try
			{
				string sortOrder = "Name";

                if (this.ViewState["CustodianSortOrder"] != null)
                {
                    sortOrder = (string)this.ViewState["CustodianSortOrder"];
                }
                if (!this.paging)
                {
                    this.AddAlphabetLinks(this.custodianLetters.Count > 0);
                    this.AddSelectorButtons();
                }
			}
			    catch (Exception ex)
			{
                Logger.LogError(ex, this.currentCase);
			}
		}

        #endregion

        #region GetCustodianUniqueId

        private string GetCustodianUniqueId(Custodian custodian)
		{
			return "C" + this.ClientID + "C" + custodian.ParentCase.Id.ToString("N") + "C" +
				custodian.Id + "C";
		}

        #endregion

        #region AddGridCustodianRow

        private void AddGridCustodianRow(Custodian custodian)
		{
			string uniqueId = this.GetCustodianUniqueId(custodian);

			this.AddGridRow();

			HtmlTableCell cell = this.CreateGridCell();
			cell.ID = "";
			cell.Width = "20";

            if (custodian.Name != null && 
                !string.IsNullOrEmpty(custodian.Name.LastName))
            {
                string letter = custodian.Name.LastName.Substring(0, 1).ToUpper();
                if (!this.custodianLetters.ContainsKey(letter))
                {
                    this.custodianLetters.Add(letter, cell.ClientID);
                }
            }

			HtmlInputCheckBox checkBox = new HtmlInputCheckBox();
			checkBox.ID = uniqueId + custodian.Status.ToString().Replace(" ", "");
			checkBox.ID += custodian.IsInternal ? "Internal" : "External";
			checkBox.EnableViewState = false;
			checkBox.Checked = this.checkedCustodians.Contains(custodian);
			cell.Controls.Add(checkBox);

            if (string.IsNullOrEmpty(custodian.Email))
            {
                checkBox.Attributes.Add("disabled", "disabled");
            }

			cell = this.CreateGridCell();

			HtmlAnchor anchor = new HtmlAnchor();
			anchor.InnerText = custodian.Name.FullName;
            anchor.HRef = string.Format("{0}/Lists/Custodians/DispForm.aspx?ID={1}", 
                custodian.ParentCase.SiteAddress.AbsolutePath, custodian.Id);
			cell.Controls.Add(anchor);

			cell = this.CreateGridCell();

			string historyOnClick = "javascript: document.getElementById('" +
				this.historyHidden.UniqueID + "').value = '" + uniqueId + "';";

			LinkButton historyButton = new LinkButton();
			historyButton.Text = custodian.Status.ToString();
			historyButton.Attributes.Add("onclick", historyOnClick);
			cell.Controls.Add(historyButton);
		}

        #endregion

        #region AddAlphabetLinks

        private void AddAlphabetLinks(bool makeHot)
		{
			HtmlTableRow mainRow = this.CreateRow();

			HtmlTableCell cell = new HtmlTableCell();
			cell.Style.Add("border-bottom", "1px solid #e4e4e4");
			cell.Style.Add("border-left", "1px solid #e4e4e4");
			cell.Style.Add("border-right", "1px solid #e4e4e4");
			cell.Style.Add("padding", "2px");
            mainRow.Cells.Add(cell);

			HtmlTable table = new HtmlTable();
			table.CellSpacing = 0;
			table.CellPadding = 0;
			table.Border = 0;
			table.Width = "100%";
			cell.Controls.Add(table);

            HtmlTableRow lettersRow = new HtmlTableRow();
            table.Rows.Add(lettersRow);

			string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            char[] letters = alphabet.ToCharArray();
            string activeLetter = string.Empty;
			
			foreach (string custodianLetter in this.custodianLetters.Keys)
			{
				activeLetter = custodianLetter;
				break;
			}

            HtmlTableCell anchorCell = null;
            HtmlTableCell emptyAnchorCell = null;

            foreach (char letterChar in letters)
			{
				string letter = letterChar.ToString();

                anchorCell = new HtmlTableCell();
                anchorCell.Width = "15";
                lettersRow.Cells.Add(anchorCell);
				
				if (!makeHot)
				{
                    anchorCell.InnerText = letter;
				}
				else
				{
                    if (this.custodianLetters.ContainsKey(letter))
                    {
                        activeLetter = letter;
                    }
		
					HtmlAnchor anchor = new HtmlAnchor();
					anchor.HRef = "javascript: scrollDivTo('" + this.GridDivClientID +
						"', '" + (string)this.custodianLetters[activeLetter] + "');";
					anchor.InnerText = letter;
                    anchorCell.Controls.Add(anchor);
				}

				if (letter != "Z")
				{
                    emptyAnchorCell = new HtmlTableCell();
                    lettersRow.Cells.Add(emptyAnchorCell);
				}
			}
		}

        #endregion

        #region AddSelectorButtons

        private void AddSelectorButtons()
		{
			HtmlTableRow row = this.CreateRow();

			HtmlTableCell cell = new HtmlTableCell();
			cell.Style.Add("padding-top", "5px");
			row.Cells.Add(cell);

			HtmlTable table = new HtmlTable();
			table.CellSpacing = 0;
			table.CellPadding = 0;
			table.Border = 0;
			table.Width = "100%";
			cell.Controls.Add(table);

			row = new HtmlTableRow();
			table.Rows.Add(row);

			this.AddSelectorButton(row, "Select All", "selectAll", true);
			this.AddSelectorButton(row, "Select Unsent", "selectUnsent", true);
			this.AddSelectorButton(row, "Select Unack.", "selectUnacknowledged", true);
			this.AddSelectorButton(row, "Deselect All", "deselectAll", false);

			row = new HtmlTableRow();
			row.Style.Add("padding-top", "5px");
			table.Rows.Add(row);

			this.AddSelectorButton(row, "Internal/Unsent", "selectInternalUnsent", true);
			this.AddSelectorButton(row, "Internal/Unack.", "selectInternalUnack", true);
			this.AddSelectorButton(row, "External/Unsent", "selectExternalUnsent", true);
			this.AddSelectorButton(row, "External/Unack.", "selectExternalUnack", false);
		}

        #endregion

        #region AddSelectorButton

        private void AddSelectorButton(HtmlTableRow row, string text, 
            string scriptFunction, bool addSpaceAfter)
		{
			HtmlTableCell cell = new HtmlTableCell();
			cell.Width = "25%";
			row.Cells.Add(cell);

			HtmlInputButton button = new HtmlInputButton();
			button.Value = text;
			button.EnableViewState = false;
            button.Attributes.Add("onclick", scriptFunction + "();");
			button.Style.Add("font-size", "8pt");
			button.Style.Add("width", "100%");
			cell.Controls.Add(button);

			if (addSpaceAfter)
			{
				cell = new HtmlTableCell();
				cell.InnerHtml = "&nbsp;";
				cell.Width = "5";
				row.Cells.Add(cell);
			}
		}

        #endregion

        #region SortButtonClick

        private void SortButtonClick(object sender, EventArgs e)
		{
			this.ViewState["CustodianSortOrder"] = ((LinkButton)sender).Text;
        }

        #endregion
    }
}
